package com.ykdl.app.Utils;


import java.util.Calendar;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.widget.Toast;

import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.JsonRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.ykdl.app.Utils.DownloadAPK.DownloadBinder;
import com.ykdl.app.base.QLog;
import com.ykdl.app.bean.VersionUpgrade;
import com.ykdl.app.common.MyApplication;
import com.ykdl.app.connect.Constants;
import com.ykdl.app.connect.NetConfig;


public class VersionUdgrateUtil {
	private static final String PROMPT_UPDATE_DATE = "prompt_update_date_";
	private static SharedPreferences settings;
	private static SharedPreferences.Editor editor;
	private VersionUpgrade  versionUpgrade = null;
	private static Context  context;
	private Calendar c;
	private LiteHttp client;
	private DownloadBinder binder;
	private boolean from=false; //判定是否是从设置页调用的监测版本方法
	static{
		
			//初始化配置文件
			if (editor == null) {
				if (settings == null) {
					settings =MyApplication.getInstance().getSharedPreferences("version", Context.MODE_PRIVATE);
					editor = settings.edit();
				} else {
					editor = settings.edit();
				}
			}
			
	}
	public  VersionUdgrateUtil(Context  context,boolean from1){
		this.context = context;
		from=from1;
		c = Calendar.getInstance();
	}
	/**
	 * 检测版本是否需要更新
	 */
	public  void checkVersionUdgrate(){
		getDataForVersionUpgrade();
	}
	
	/**
	 * 检测版本是否需要更新
	 */
	public  void checkVersionUdgrateForTime(){
		//获得提示更新时间(每三天进行检测一次，如有新版本进行更新。)
		long prompt_update_date = settings.getLong(PROMPT_UPDATE_DATE, 0);
		if(c.getTimeInMillis() > prompt_update_date){
			if(!isConnect())return;
				getDataForVersionUpgrade();
		}
	}
	/**
	 * 检测版本是否需要更新
	 */
	public  void checkVersionUdgrateForTime(boolean isSetting){
		//获得提示更新时间(每三天进行检测一次，如有新版本进行更新。)
			if(!isConnect())return;
				getDataForVersionUpgrade();
	}
	
	/**
	 * 网络获取版本号数据
	 */
	private  void getDataForVersionUpgrade() {
		if(from){
			showProgress();
		}
		client = MyApplication.getInstance().getLiteHttp();
		client.getConfig().restoreToDefault();
		String url = NetConfig.TEST_SERVERS+"/api/v1/application/version";
		JsonRequest<VersionUpgrade> cacheRequest1 = new JsonRequest<VersionUpgrade>(
				url, VersionUpgrade.class);
		cacheRequest1.addUrlParam("client_id", Constants.CLIENT_ID);
		cacheRequest1.addUrlParam("client_version", MobileUtils.getStringVersion()+"");
		cacheRequest1.setMethod(HttpMethods.Get);
		cacheRequest1.setHttpListener(new HttpListener<VersionUpgrade>() {
			@Override
			public void onSuccess(VersionUpgrade user,
					Response<VersionUpgrade> response) {
				dismissProgress();
				if(user!=null){
					System.out.println("versionUpgrade : " + response);
					versionUpgrade = (VersionUpgrade)user;
					compareVersion(versionUpgrade);
				}
			}

			@Override
			public void onFailure(HttpException e,
					Response<VersionUpgrade> response) {
				Toast.makeText(context, "失败", 0).show();
				dismissProgress();
			}
		});
		client.executeAsync(cacheRequest1);
		
	
	}
	public ProgressDialog progress;
	
	public void showProgress(){
		progress = ProgressDialog.show(context, "检测版本...", "检测中...", true, false);  
	}
	public void dismissProgress(){
		if (progress!=null) {
			
			progress.dismiss();
		}
	}
	/***
	 * 比较版本号
	 * @param version
	 */
	private void compareVersion(VersionUpgrade version){
		if (version.getLatest_version()!=null) {
			if(Float.parseFloat(MobileUtils.getStringVersion())<(version.getLatest_version().getVersion())){
				showUpdateDialog();
			}else {
				if(from){
					Toast.makeText(context, "已经是最新版本", 1).show();
				}
			}
		}else {
//			Toast.makeText(context, "已经是最新版本", 1).show();
		}
	}
	
	/**
	 * 提示升级对话框
	 */
	private void showUpdateDialog() {
		/*DialogImpl  dialog = new DialogImpl();
		if(versionUpgrade.isForce_update()){//强制升级
			dialog.showDialog(context, "检测到新版本", "是否下载更新?", false, new DialogCallBack() {
				@Override
				public void onClick(int what) {
					switch (what) {
					case IDialog.YES://升级
						recoredCheckUpdateTime();
						commondDownlodTask();
						break;
					case IDialog.CANCLE://退出程序，强制升级
						KidApp.getInstance().getAppManager().AppExit(context, false);
						break;
					default:
						break;
					}
				}
			});
		}else{
			dialog.showDialog(context, "检测到新版本", "是否下载更新?", false, new DialogCallBack() {
				@Override
				public void onClick(int what) {
					switch (what) {
					case IDialog.YES://升级
						recoredCheckUpdateTime();
						commondDownlodTask();
						break;
					case IDialog.CANCLE://暂不升级
						recoredCheckUpdateTime();
						break;
					default:
						break;
					}
				}
			});
		}*/
	if(versionUpgrade.isForce_update()){//强制升级
		new AlertDialog.Builder(context).setTitle("版本升级").
		setMessage("检测到新版本,是否下载更新?").
		setPositiveButton("升级", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				recoredCheckUpdateTime();
				commondDownlodTask();
			}
		}).show();
	}else{
		new AlertDialog.Builder(context).setTitle("版本升级").
		setMessage("检测到新版本,是否下载更新?").
		setPositiveButton("升级", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				recoredCheckUpdateTime();
				commondDownlodTask();
			}
		}).setNegativeButton("暂不升级", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				recoredCheckUpdateTime();
			}
		}).show();
	 }
		
	}
	
	 String url = null;
	 boolean isBinded = false;
	private void commondDownlodTask() {
		url = versionUpgrade.getLatest_version().getApp_url();
//		url = "http://bcscdn.baidu.com/new-repackonline/appsearch/AndroidPhone/1.0.21.64/1/1426l/appsearch_AndroidPhone_1-0-21-64_1426l.apk?response-content-disposition=attachment;filename=appsearch_AndroidPhone_1426l.apk&response-content-type=application/vnd.android.package-archive";
		if(url != null && !"".equals(url)){
			Intent intent = new Intent(context, DownloadAPK.class);
			context.startService(intent);
			context.bindService(intent, conn, Context.BIND_AUTO_CREATE);
		}
	}
	
	/**
	 * //记录更新日期时间
	 */
	private void recoredCheckUpdateTime() {
		//每个三天提醒升级
		c.add(Calendar.DAY_OF_MONTH, 3);
		editor.putLong(PROMPT_UPDATE_DATE, c.getTimeInMillis());
		editor.commit();
	}
	ServiceConnection conn = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			isBinded = false;
		}
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			binder = (DownloadBinder) service;
			isBinded = true;
			binder.start(url);
		}
	};
	
	
	/*public void cannelService(){
		if (isBinded) {
			KidApp.getInstance().getApplicationContext().unbindService(conn);
		}
		if (binder != null && binder.isDownLoading()) {
			binder.cancel();//取消下载
			Intent it = new Intent(KidApp.getInstance().getApplicationContext(), DownloadAPK.class);
			KidApp.getInstance().getApplicationContext().stopService(it);//停止服务
		}
	}*/
	public static boolean isConnect() {
		// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
		try {
			ConnectivityManager connectivity = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				// 获取网络连接管理的对象
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					// 判断当前网络是否已经连接
					// if (info.getState() == NetworkInfo.State.CONNECTED) {
					return true;
					// }
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			QLog.debug("error", e.toString());
		}
		return false;
	}
}
